使用代码下载
1 package cn.servlet; 2 3 import java.io.FileInputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.OutputStream; 7 import java.net.URLEncoder; 8 9 import javax.servlet.ServletException;10 import javax.servlet.http.HttpServlet;11 import javax.servlet.http.HttpServletRequest;12 import javax.servlet.http.HttpServletResponse;13 14 public class DownServlet extends HttpServlet {15 @Override16 public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {17 System.err.println("判断用户的积分信息.....");18 //获取真实的文件19 String path = getServletContext().getRealPath("/files/cos.jar");20 //获取这个文件的io21 InputStream in = 22 new FileInputStream(path);23 //设置响应的头信息24 //如果希望将下载的文件修改成中文名,则必须要对中文名称进行编码25 String name = "下载的文件.jar";26 name = URLEncoder.encode(name,"UTF-8");27 resp.setHeader("Content-Disposition","attachment;filename="+name);28 resp.setContentType("application/force-download");29 30 byte[] bs = new byte[1024];31 OutputStream out = 32 resp.getOutputStream();33 int len = 0;34 while((len=in.read(bs))!=-1){35 out.write(bs,0,len);36 }37 in.close();38 out.close();39 }40 }41 42 43 下载44 45 Download
自己使用urlconnection实现下载
1 package cn.client; 2 3 import java.io.FileOutputStream; 4 import java.io.InputStream; 5 import java.io.OutputStream; 6 import java.net.HttpURLConnection; 7 import java.net.URL; 8 public class Client { 9 public static void main(String[] args) throws Exception {10 //1:声明url地址11 URL url = new URL("http://localhost:8080/20151116/files/cos.jar");12 HttpURLConnection con = 13 (HttpURLConnection) url.openConnection();14 con.setRequestMethod("GET");15 con.setDoOutput(true);16 con.setDoInput(true);17 con.setConnectTimeout(3000);18 con.connect();19 20 //获取连接的状态21 int code = con.getResponseCode();22 if(code==200){23 InputStream in = 24 con.getInputStream();25 byte[] bs = new byte[1024];26 int len = 0;27 OutputStream out = new FileOutputStream("d:/a/a.jar");28 while((len=in.read(bs))!=-1){29 out.write(bs, 0, len);30 }31 out.close();32 in.close();33 }34 con.disconnect();35 }36 }